package com.mlm.mlmapp.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.Constants;
import com.mlm.mlmapp.cons.HTTPCons;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DimensionRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.studio_list)
public class StudioListActivity extends BaseActivity implements HTTPCons, OnClickListener {
    public static final int REQUEST_CODE = 11;
    @DimensionRes(R.dimen.recyclerview_sylist_space)
    float commentImagesMargin;
    @DimensionRes
    float comments_images_edge;
    @ViewById
    TextView tv_no_title;
    private AQuery aq;
    private StudiosListAdapter adapter;
    List<JSONObject> studiosListDataset;
    @ViewById
    RecyclerView rv_studio;
    JSONObject json;

    @AfterViews
    public void init() {
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        studiosListDataset = new ArrayList<>();
        aq.progress(new AQProgressDialog(this)).ajax(get_studios_action + "?cityName=" + Constants.CITY, JSONArray.class,
                new AjaxCallback<JSONArray>() {

                    @Override
                    public void callback(String url, JSONArray array,
                                         AjaxStatus status) {
                        // TODO Auto-generated method stub
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络", Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() != 200) {
                            Toast.makeText(aq.getContext(),
                                    "网络异常:" + status.getCode(),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj;
                                try {
                                    obj = array.getJSONObject(i);
                                    studiosListDataset.add(obj);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                            adapter.notifyDataSetChanged();

                        }
                    }

                });

        final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);

        rv_studio.setLayoutManager(layoutManager);
        rv_studio.setItemAnimator(new RecyclAnimation());
        adapter = new StudiosListAdapter(StudioListActivity.this,
                studiosListDataset);
        rv_studio.setAdapter(adapter);
    }

    class StudiosListAdapter extends
            RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private Context mContext;
        private List<JSONObject> array;
        private OnClickListener l;

        public StudiosListAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.array = array;
            this.l = (OnClickListener) con;
        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        public boolean isPositionHeader(int position) {
            return position == 0;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                          int viewType) {
            // TODO Auto-generated method stub

            final StudiosViewHolder holder = new StudiosViewHolder(
                    LayoutInflater.from(StudioListActivity.this).inflate(
                            R.layout.studio_list_item, parent, false));
            return holder;

        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder,
                                     int position) {
            // TODO Auto-generated method stub
            final StudiosViewHolder vholder = (StudiosViewHolder) holder;
            json = array.get(position);
            vholder.tv_studio_name.setText(getJsonString(json, "names"));
            vholder.tv_studio_address.setText(getJsonString(json, "addr"));
            aq.id(vholder.iv_studio_url).image(getJsonString(json, "photoUrl"),
                    false, true, 200, 0, null, com.androidquery.util.Constants.FADE_IN);
//			vholder.tv_tel.setText(getString(R.string.studio_tel,
//					getJsonString(json, "phone")));
            vholder.tv_tel.setText(getJsonString(json, "phone"));
            vholder.tv_tel.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            vholder.tv_tel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //调用系统的拨号服务实现电话拨打功能
                    //封装一个拨打电话的intent，并且将电话号码包装成一个Uri对象传入
                    dialog1(vholder.tv_tel.getText().toString());

                }
            });
            holder.itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    v.setTag(json);
                    l.onClick(v);
                }
            });

        }

        public class StudiosViewHolder extends RecyclerView.ViewHolder {
            String id;
            TextView tv_tel;
            TextView tv_studio_address;
            TextView tv_studio_name;
            ImageView iv_studio_url;

            public StudiosViewHolder(View itemView) {
                super(itemView);
                this.tv_studio_name = (TextView) itemView
                        .findViewById(R.id.tv_studio_name);
                this.tv_studio_address = (TextView) itemView
                        .findViewById(R.id.tv_studio_address);
                this.tv_tel = (TextView) itemView.findViewById(R.id.tv_tel);
                this.iv_studio_url = (ImageView) itemView.findViewById(R.id.iv_studio_url);
            }
        }
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
//		Intent data=new Intent();
//		JSONObject json=(JSONObject)arg0.getTag();
//		data.putExtra("id",getJsonString(json,"id"));
//		data.putExtra("name",getJsonString(json,"names"));
//		this.setResult(1, data);
//		this.finish();
    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Intent data = new Intent();
        setResult(RESULT_CANCELED, data);
        this.finish();
    }

    private void dialog1(String mobile) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
        builder.setMessage(mobile); //设置内容
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog

            }
        });
        builder.setNegativeButton("呼叫", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + getJsonString(json, "phone")));
                StudioListActivity.this.startActivity(intent);//内部类
                dialog.dismiss(); //关闭dialog
            }
        });

        builder.create().show();
    }
}
